package com.moba.service;

import com.moba.domain.*;
import com.moba.emums.*;
import com.moba.emums.roleUser.InitPassword;
import com.moba.mapper.UserInfoMapper;
import com.moba.mapper.UserWalletMapper;
import com.moba.util.HDWalletModel;
import com.moba.util.WalletHelp;
import com.moba.utils.encrypt.DESPlusUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liu, jia
 * @version 2019-02-20 09:59
 * @date 2019-02-20 09:59
 */
@Service
@Transactional
public class UserInfoService {

  @Resource private UserInfoMapper userInfoMapper;

  @Resource private UserWalletMapper UserWalletMapper;

  @Resource private UserBiRecordService userBiRecordService;

  @Resource private UserRelationService userRelationService;

  @Resource private UserRelationParService userRelationParService;

  @Resource private UserInfoService userInfoService;

  @Resource private SysSettingService sysSettingService;

  @Resource private BaseDataService baseDataService;

  protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(OrderInfoService.class);

  public UserInfo getEntity(UserInfo t) {
    return this.userInfoMapper.selectEntity(t);
  }

  public Integer getEntityCount(UserInfo t) {
    return this.userInfoMapper.selectEntityCount(t);
  }

  public BigDecimal getEntitySumUsdt(UserInfo t) {
    return this.userInfoMapper.selectEntitySumUsdt(t);
  }

  public BigDecimal getTeamLeijiMoneySum(UserInfo t) {
    return this.userInfoMapper.selectEntityTeamLeijiMoneySum(t);
  }

  public List<UserInfo> getEntityList(UserInfo t) {
    return this.userInfoMapper.selectEntityList(t);
  }

  private static String getMobile() {

    String[] telFirst =
        "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(",");
    int index = getNum(0, telFirst.length - 1);
    String first = telFirst[index];
    String second = String.valueOf(getNum(1, 888) + 10000).substring(1);
    String third = String.valueOf(getNum(1, 9100) + 10000).substring(1);
    return first + second + third;
  }

  public static int getNum(int start, int end) {
    return (int) (Math.random() * (end - start + 1) + start);
  }

  public String getUserMobile(String mobile) {
    UserInfo b = new UserInfo();
    b.setMobile(mobile);
    b.setIsDel(0);
    int mobileUserCount = userInfoService.getEntityCount(b);
    if (mobileUserCount > 0) {
      getUserMobile(getMobile());
    }
    return mobile;
  }

  public Integer createEntity(UserInfo t) {

    if (null != t.getMap().get("insert_user_test")) {
      Integer count = new Integer(t.getMap().get("insert_user_test").toString());
      UserInfo a = null;
      DESPlusUtils des = null;
      String password = "";
      String ymid = "13856147372";
      if (null != t.getMap().get("ymid")) {
        ymid = t.getMap().get("ymid").toString();
      }
      try {
        des = new DESPlusUtils();
        password = des.encrypt(InitPassword.INIT_PWD);
      } catch (Exception e) {
        e.printStackTrace();
      }
      String parMobile = "";

      for (int i = 0; i < count; i++) {
        logger.info("====第" + i + "个===");
        if (i == 0) {
          parMobile = ymid;
        }
        if (null != t.getMap().get("ymid")) {
          parMobile = t.getMap().get("ymid").toString();
        }
        parMobile = insertTestUser(password, parMobile);
      }
      logger.info("==========结束=====");

      return 1;
    }

    this.userInfoMapper.insertEntity(t);

    if (null != t.getMap().get("insert_user_realtion")) {

      insertUserRealtion(t);
    }

    return t.getId();
  }

  public void insertUserRealtion(UserInfo t) {
    this.insertUserRelationAndPar(t.getId(), t.getYmid());
    UserWallet wallet = new UserWallet();
    wallet.setUserId(t.getId());
    HDWalletModel ecr20ohdw = WalletHelp.createECR20Wallet(t.getPassword());
    // HDWalletModel    usdthdw  = WalletHelp.createUSDTWallet( t.getPassword());

    wallet.setPassword(t.getPassword());
    wallet.setEcr20Address(ecr20ohdw.getAddress());
    wallet.setEcr20PriKey(ecr20ohdw.getPrivateKey());
    wallet.setEcr20PubKey(ecr20ohdw.getPublicKey());
    wallet.setEcr20Balance(0.0);
    wallet.setCreateTime(new Date());
    wallet.setPassword(t.getPassword());
    wallet.setStatus(1); // 正常状态

    // wallet.setUsdtAddress(usdthdw.getAddress());
    // wallet.setUsdtPriKey(usdthdw.getPrivateKey());
    // wallet.setUsdtPubKey(usdthdw.getPublicKey());
    // wallet.setUsdtBalance(0.0);
    UserWalletMapper.insertEntity(wallet);
  }

  public String insertTestUser(String password, String ymid) {
    UserInfo a;
    a = new UserInfo();
    a.setMobile(getUserMobile(getMobile()));
    a.setUserName(a.getMobile());
    a.setUserType(2);
    a.setUserLevel(200);
    a.setPassword(password);
    a.setSafePassword(password);
    a.setYmid(ymid);
    a.setOrderMoneySum(new BigDecimal(20000));

    userInfoService.createEntity(a);

    insertUserRealtion(a);

    return a.getMobile();
  }

  public int updateEntity(UserInfo t) {
    // 发放团队奖励
    if (null != t.getMap().get("sned_team_price")) {
      logger.info("=====发放团队奖励=====开始");

      SimpleDateFormat sdFormatYmd = new SimpleDateFormat("yyyy-MM-dd");

      SysSetting s = new SysSetting();
      s.setMemo(SysSettingType.dayCountRetrun.getIndex());
      s = sysSettingService.getEntity(s);
      int day = Integer.valueOf(s.getContent());

      UserInfo a = new UserInfo();
      a.setIsDel(0);
      List<UserInfo> alist = userInfoService.getEntityList(a);
      for (UserInfo item : alist) {

        if (item.getUserLevel() == UserLevel.USER_LEVEL_200.getIndex()) {
          continue;
        }

        //        UserRelationPar b = new UserRelationPar();
        //        b.setUserParId(item.getId());
        //        BigDecimal sumMoneyLeiji = userRelationParService.getUserSonSumMoneyLeiji(b);
        //        logger.info("===该用户团队收益总和:" + sumMoneyLeiji);

        // 计算当天业绩
        UserBiRecord c = new UserBiRecord();
        c.setAddUserId(item.getId());
        c.setBiType(BiType.BI_TYPE_200.getIndex());
        c.setBiGetType(BiGetType.BI_GET_TYPE_2.getIndex());
        c.setBiChuOrRu(1);
        c.getMap().put("st_add_date", sdFormatYmd.format(new Date()));
        c.getMap().put("en_add_date", sdFormatYmd.format(new Date()));
        BigDecimal biSum = userBiRecordService.getEntityBiSum(c);
        logger.info("=========biSum:" + biSum.toString());
        if (biSum.compareTo(new BigDecimal(0)) == 0) {
          continue;
        }

        BaseData userData = new BaseData();
        userData.setId(item.getUserLevel());
        userData = baseDataService.getEntity(userData);

        BigDecimal rale =
            new BigDecimal(userData.getTypeValue().intValue()).divide(new BigDecimal(100));
        //        logger.info("===sumMoneyLeiji:" + sumMoneyLeiji);
        logger.info("===rale:" + rale);

        BigDecimal biNo = biSum.multiply(rale);
        logger.info("====奖励金额:" + biNo);
        userInfoService.updateBi(
            item.getId(),
            item.getId(),
            BiGetType.BI_GET_TYPE_30.getIndex(),
            BiType.BI_TYPE_500.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            biNo,
            null);
      }
      logger.info("=====发放团队奖励=====结束");
      return 1;
    }

    int flag = this.userInfoMapper.updateEntity(t);

    // 添加充值矿源记录
    if (null != t.getMap().get("addOrderMoneySum")) {
      if (null != t.getId()) {
        userBiRecordService.addBiRecord(
            t.getId(),
            t.getId(),
            BiGetType.BI_GET_TYPE_80.getIndex(),
            BiType.BI_TYPE_400.getIndex(),
            1,
            new BigDecimal(t.getMap().get("addOrderMoneySum").toString()),
            null);
      } else {
        System.out.println(t.getMap().get("pksStr").toString());
        String pks[] = t.getMap().get("pksStr").toString().split(",");
        System.out.println("pks.length:" + pks.length);
        if (null != pks && pks.length > 0) {
          for (String cur : pks) {
            System.out.println("cur:" + cur);
            userBiRecordService.addBiRecord(
                new Integer(cur),
                new Integer(cur),
                BiGetType.BI_GET_TYPE_80.getIndex(),
                BiType.BI_TYPE_400.getIndex(),
                1,
                new BigDecimal(t.getMap().get("addOrderMoneySum").toString()),
                null);
          }
        }
      }
    }

    // 发放同级奖励
    if (t.getMap().get("send_tongji_price") != null) {

      // 查询当前升级用户的静态收益
      UserBiRecord userBiRecord = new UserBiRecord();
      userBiRecord.setAddUserId(t.getId());
      userBiRecord.setBiGetType(BiGetType.BI_GET_TYPE_1.getIndex());
      BigDecimal sum_money = userBiRecordService.getEntityBiSum(userBiRecord);

      BigDecimal rate = new BigDecimal(String.valueOf(0.1));

      BaseData data = new BaseData();
      data.setType(BaseDataType.BaseDataType_70.getIndex());
      data.setLinkId(t.getUserLevel());
      data = baseDataService.getEntity(data);

      if (data != null && data.getPreData() != null) {
        rate = new BigDecimal(data.getPreData());
      }

      BigDecimal tongji_price = sum_money.multiply(rate);

      int MaxLevelCount = 20;

      // 查询系统设置奖励最高代数 默认20代
      SysSetting sys = new SysSetting();
      sys.setMemo("MaxLevelCount");
      sys = sysSettingService.getEntity(sys);

      if (null != sys) {
        MaxLevelCount = Integer.valueOf(sys.getContent());
      }

      // 查询
      UserRelationPar userRelationPar = new UserRelationPar();
      userRelationPar.setUserId(t.getId());
      userRelationPar.getMap().put("userParLevelLe", MaxLevelCount);
      userRelationPar.getMap().put("orderBy", "a.USER_PAR_LEVLE asc");
      List<UserRelationPar> list = userRelationParService.getEntityList(userRelationPar);

      if (null != list && list.size() > 0) {

        for (UserRelationPar temp : list) {
          UserInfo userInfo = new UserInfo();
          userInfo.setId(temp.getUserParId());
          userInfo = userInfoService.getEntity(userInfo);
          if (userInfo != null
              && userInfo.getUserLevel().intValue() == t.getUserLevel().intValue()) {
            userInfoService.updateBi(
                temp.getUserParId(),
                t.getId(),
                BiGetType.BI_GET_TYPE_50.getIndex(),
                BiType.BI_TYPE_300.getIndex(),
                BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                tongji_price,
                null);
            break;
          }
        }
      }
    }

    return flag;
  }

  /** 通过基础数据id，查找对应的基础数据 */
  public BaseData getBaseDataById(Integer id) {
    BaseData baseData = new BaseData();
    baseData.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    baseData.setId(id);
    return this.baseDataService.getEntity(baseData);
  }

  public int removeEntity(UserInfo t) {
    return this.userInfoMapper.deleteEntity(t);
  }

  public List<UserInfo> getEntityPaginatedList(UserInfo t) {
    return this.userInfoMapper.selectEntityPaginatedList(t);
  }

  public Integer getEntityTeamCount(UserInfo t) {
    return this.userInfoMapper.selectEntityTeamCount(t);
  }

  public List<UserInfo> getEntityTeamPaginatedList(UserInfo t) {
    return this.userInfoMapper.selectEntityTeamPaginatedList(t);
  }

  /**
   * 增加账单记录，同时把用户的余额更新成最新的余额
   *
   * @param userId(用户id)
   * @param biGetType(枚举BiGetType中余额出入方式)
   * @param biType(枚举BiType中余额是什么类型的数据比如是金币还是积分还是钱)
   * @param biChuOrRu(枚举BiChuOrRu中余额是减少还是增加)
   * @param biNo(余额的增加或者减少的量)
   * @param orderId(订单的id)
   * @return
   * @author ding, ning
   */
  public Boolean updateBi(
      Integer userId,
      Integer linkId,
      Integer biGetType,
      Integer biType,
      Integer biChuOrRu,
      BigDecimal biNo,
      Integer orderId) {

    boolean addBiRecordFlag =
        userBiRecordService.addBiRecord(
            userId, linkId, biGetType, biType, biChuOrRu, biNo, orderId);

    if (addBiRecordFlag) {
      UserInfo userInfo = new UserInfo();
      userInfo.setId(userId);
      // 平台电子币GHMI
      if (biType.intValue() == BiType.BI_TYPE_100.getIndex()) {
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_1.getIndex()) {
          userInfo.getMap().put("addBiDianZi", biNo);
        }
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_X1.getIndex()) {
          userInfo.getMap().put("subBiDianZi", biNo);
        }
      }
      // 用户业绩量
      if (biType.intValue() == BiType.BI_TYPE_200.getIndex()) {
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_1.getIndex()) {
          userInfo.getMap().put("addLeijiMoneyUser", biNo);
        }
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_X1.getIndex()) {
          userInfo.getMap().put("subLeijiMoneyUser", biNo);
        }
      }
      // 用户奖励获得的USDT
      if (biType.intValue() == BiType.BI_TYPE_300.getIndex()) {
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_1.getIndex()) {
          userInfo.getMap().put("addBiUsdt", biNo);
        }
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_X1.getIndex()) {
          userInfo.getMap().put("subBiUsdt", biNo);
        }
      }

      // 矿源
      if (biType.intValue() == BiType.BI_TYPE_400.getIndex()) {
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_1.getIndex()) {
          userInfo.getMap().put("addOrderMoneySum", biNo);
        }
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_X1.getIndex()) {
          userInfo.getMap().put("subOrderMoneySum", biNo);
        }
      }

      // 用户奖励获得的GUSD
      if (biType.intValue() == BiType.BI_TYPE_500.getIndex()) {
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_1.getIndex()) {
          userInfo.getMap().put("addGusd", biNo);
        }
        if (biChuOrRu.intValue() == BiChuOrRu.BI_CHU_OR_RU_X1.getIndex()) {
          userInfo.getMap().put("subGusd", biNo);
        }
      }

      int count = userInfoMapper.updateEntity(userInfo);
      if (count <= 0) {
        addBiRecordFlag = false;
      }
    }
    return addBiRecordFlag;
  }

  public void insertUserRelationAndPar(Integer user_id, String ym_id) {

    UserInfo userInfoPar = new UserInfo();
    userInfoPar.setIsDel(0);
    userInfoPar.getMap().put("ym_id", ym_id);
    userInfoPar = userInfoService.getEntity(userInfoPar);

    // 查询 父关系表 并且插入自己关系表 UserRelation
    UserRelation entityPar = new UserRelation();
    entityPar.setUserId(userInfoPar.getId());
    entityPar = userRelationService.getEntity(entityPar);
    if (null != entityPar) {
      UserRelation entityInsert = new UserRelation();
      entityInsert.setUserId(user_id);
      entityInsert.setAddUserId(user_id);
      entityInsert.setAddDate(new Date());
      entityInsert.setUserParId(entityPar.getUserId());
      entityInsert.setUserRootId(entityPar.getUserParId());
      int insertFlag = userRelationService.createEntity(entityInsert);
      if (insertFlag > 0) { // 如果插入成 则再插入UserRelationPar
        List<UserRelation> parentList = new ArrayList<UserRelation>();
        List<UserRelation> getParentList =
            this.getUserRelationParentList(entityPar.getUserId(), parentList);
        if (null != getParentList && getParentList.size() > 0) {
          int i = 1;
          for (UserRelation temp : getParentList) {
            UserRelationPar userRelationParInsert = new UserRelationPar();
            userRelationParInsert.setAddDate(new Date());
            userRelationParInsert.setUserId(user_id);
            userRelationParInsert.setUserParId(temp.getUserId());
            userRelationParInsert.setUserParLevle(i);
            userRelationParService.createEntity(userRelationParInsert);
            i++;
          }
        }
      }
    }
  }

  /**
   * 查询所有的父节点
   *
   * @return List<UserRelation>
   */
  public List<UserRelation> getUserRelationParentList(
      Integer user_par_id, List<UserRelation> parentList) {

    UserRelation entity = new UserRelation();
    entity.setUserId(user_par_id);
    entity = userRelationService.getEntity(entity);
    if (null != entity) {
      parentList.add(entity);
      this.getUserRelationParentList(entity.getUserParId(), parentList);
    }
    return parentList;
  }

  /**
   * 查询所有的子节点
   *
   * @return List<UserRelation>
   */
  public List<UserRelation> getUserRelationSonList(Integer user_id, List<UserRelation> sonList) {

    UserRelation entity = new UserRelation();
    entity.setUserParId(user_id);
    List<UserRelation> entityList = userRelationService.getEntityList(entity);
    if (null != entityList && entityList.size() > 0) {
      for (UserRelation temp : entityList) {
        sonList.add(temp);
        this.getUserRelationSonList(temp.getUserId(), sonList);
      }
    }
    return sonList;
  }

  /** 发放团队静态收益以及领导分红，增加记录 */
  public void teamPrice(Integer user_id, Integer order_id, BigDecimal bonus) {

    int MaxLevelCount = 20;

    // 查询系统设置奖励最高代数 默认20代
    SysSetting sys = new SysSetting();
    sys.setMemo("MaxLevelCount");
    sys = sysSettingService.getEntity(sys);

    if (null != sys) {
      MaxLevelCount = Integer.valueOf(sys.getContent());
    }

    // 查询
    UserRelationPar userRelationPar = new UserRelationPar();
    userRelationPar.setUserId(user_id);
    userRelationPar.getMap().put("userParLevelLe", MaxLevelCount);
    userRelationPar.getMap().put("orderBy", "a.USER_PAR_LEVLE asc");
    List<UserRelationPar> list = userRelationParService.getEntityList(userRelationPar);

    if (null != list && list.size() > 0) {
      int max_user_level = UserLevel.USER_LEVEL_200.getIndex();
      BigDecimal rate = new BigDecimal(0);
      for (UserRelationPar temp : list) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(temp.getUserParId());
        userInfo = userInfoService.getEntity(userInfo);
        // 用户不存在或者没有消费的直接跳过，没有奖励
        if (userInfo == null || userInfo.getLeijiMoneyUser().compareTo(new BigDecimal(0)) != 1) {
          continue;
        }

        // 获取团队分红奖励比例，静态收益*team_rate
        BigDecimal team_rate = new BigDecimal(String.valueOf(0.01));

        BaseData teamData = new BaseData();
        teamData.setType(BaseDataType.BaseDataType_60.getIndex());
        teamData.setValue(temp.getUserParLevle());
        teamData = baseDataService.getEntity(teamData);

        if (teamData != null) {
          team_rate = new BigDecimal(teamData.getPreData());
        }

        BigDecimal team_price = bonus.multiply(team_rate);
        this.updateBi(
            temp.getUserParId(),
            user_id,
            BiGetType.BI_GET_TYPE_20.getIndex(),
            BiType.BI_TYPE_300.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            team_price,
            order_id);

        // 查询出用户等级大于200的k1,k2等用户
        if (userInfo.getUserLevel().intValue() > max_user_level) {
          // 获取领导分红奖励比例，静态收益*leader_rate
          BaseData leaderData = new BaseData();
          leaderData.setType(BaseDataType.BaseDataType_70.getIndex());
          leaderData.setLinkId(userInfo.getUserLevel());
          leaderData = baseDataService.getEntity(leaderData);

          if (leaderData != null && leaderData.getValue() != null) {
            BigDecimal leader_rate = new BigDecimal(leaderData.getValue()).subtract(rate);
            BigDecimal leader_price = bonus.multiply(leader_rate);

            this.updateBi(
                temp.getUserParId(),
                user_id,
                BiGetType.BI_GET_TYPE_30.getIndex(),
                BiType.BI_TYPE_300.getIndex(),
                BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                leader_price,
                order_id);
          }
          max_user_level = userInfo.getUserLevel();
          rate = new BigDecimal(leaderData.getValue());
        }
      }
    }
  }
  /** 发放加权奖励，增加记录 */
  public void WeightingPrice(Integer user_id, Integer order_id, BigDecimal bonus) {

    int userLevel = 205;
    // 查询出用户等级205的k5等用户
    UserInfo userInfo = new UserInfo();
    userInfo.setUserLevel(userLevel);
    userInfo.setIsDel(0);
    List<UserInfo> list = userInfoService.getEntityList(userInfo);
    if (list != null && list.size() > 0) {
      // 获取加权分红奖励比例，静态收益*weighting_rate
      BigDecimal weighting_rate = new BigDecimal(String.valueOf(0.3));

      // 查询系统设置加权分红比例
      SysSetting sys = new SysSetting();
      sys.setMemo("weightingRate");
      sys = sysSettingService.getEntity(sys);

      if (null != sys) {
        weighting_rate = new BigDecimal(sys.getContent());
      }

      BigDecimal weighting_price = bonus.multiply(weighting_rate);

      for (UserInfo temp : list) {

        this.updateBi(
            temp.getId(),
            user_id,
            BiGetType.BI_GET_TYPE_40.getIndex(),
            BiType.BI_TYPE_300.getIndex(),
            BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            weighting_price,
            order_id);
      }
    }
  }

  /** 查询直推团队相应等级用户个数是否满足 */
  public boolean userLevelCount(Integer user_id, int user_level) {
    boolean can_level_up = false;
    int invit_count = 3;
    BaseData base = new BaseData();
    base.setId(user_level);
    base = baseDataService.getEntity(base);
    if (base != null && base.getPreData() != null) {
      invit_count = Integer.valueOf(base.getPreData());
    }

    UserRelation userRelation = new UserRelation();
    userRelation.setUserParId(user_id);
    List<UserRelation> list = userRelationService.getEntityList(userRelation);
    int count = 0;
    if (list != null && list.size() > 0) {

      for (UserRelation temp : list) {

        UserInfo userInfo = new UserInfo();
        userInfo.setId(temp.getUserId());
        userInfo.setIsDel(0);
        userInfo = userInfoService.getEntity(userInfo);
        if (userInfo != null) {
          if (userInfo.getUserLevel().intValue() == user_level) {
            count++;
            if (count >= invit_count) {
              can_level_up = true;
              break;
            }
          }
        }
      }
    }

    return can_level_up;
  }
}
